<template>
  <view class="form-section">
    <view class="form-item">
      <text class="form-label">现场问题</text>
      <textarea
        class="form-textarea"
        v-model="form.issue"
        placeholder="请输入现场问题"
        maxlength="500"
      />
    </view>

    <view class="form-actions">
      <button class="btn-primary" :disabled="isSubmitting" @click="submit">
        {{ isSubmitting ? '提交中...' : '提交' }}
      </button>
      <view
        class="btn-warning"
        @longpress="startVoiceInput"
        @touchend="stopVoiceInput"
      >
        <uni-icons type="mic" size="28" color="#fff" />
      </view>
    </view>
	<view v-if="isRecording" class="record-hint">
	  <view class="record-icon">
	    <text class="iconfont icon-mic"></text>
	  </view>
	  <view class="record-info">
	    <text>{{ recordHintText }}</text>
	    <view class="record-volume">
	      <view v-for="i in 5" :key="i" :class="['volume-bar', i <= volumeLevel ? 'active' : '']"></view>
	    </view>
	  </view>
	</view>
  </view>
</template>

<script setup>
import { reactive, ref, defineProps, defineEmits, onMounted } from "vue";

const userInfo = uni.getStorageSync("userInfo");
const recordHintText = ref('按住说话')

const props = defineProps({
  projectInfo: {
    type: Object,
    default: null
  },
  accPerson: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['formSubmit']);

const form = reactive({
  issue: "",
  attachmentPath: ""
});

const isRecording = ref(false);
const isSubmitting = ref(false);
let recorderManager = null;

/**
 * 初始化录音管理器（与原有逻辑保持一致）
 */
const initRecorder = () => {
  if (recorderManager) return;

  recorderManager = uni.getRecorderManager();

  recorderManager.onStart(() => {
    // console.log("录音开始");
	recordHintText.value = '正在录音...'
  });

  recorderManager.onStop((res) => {
    // console.log("录音停止，临时文件路径：", res.tempFilePath);
    isRecording.value = false;
    form.attachmentPath = res.tempFilePath;
    uploadAudioForTranscription(res.tempFilePath);
  });

  recorderManager.onError((err) => {
    isRecording.value = false;
    console.error("录音出错：", err);
    uni.showToast({
      title: "录音失败",
      icon: "none"
    });
  });
};

onMounted(() => {
  initRecorder();
});

/**
 * 点击“提交”按钮时，先获取当前地理位置，获取成功后再将经纬度拼入 submitData 上报后台
 */
const submit = () => {
  if (isSubmitting.value) return;
  isSubmitting.value = true;

  // 调用 uni.getLocation 获取经纬度
  uni.getLocation({
    type: "gcj02", // 返回国测局坐标，可根据后台需求改为 "wgs84"
    success: (locationRes) => {
      const latitude = locationRes.latitude;
      const longitude = locationRes.longitude;

      // 构造要提交的参数，其中新增 latitude 与 longitude
      const submitData = {
        MIS_id: props.projectInfo?.MIS_id,
        project_name: props.projectInfo?.project_name,
        task_id: props.projectInfo?.task_id,
        task_name: props.projectInfo?.task_name,
        acc_person: props.accPerson,
        acc_problem: form.issue,
        latitude: latitude,
        longitude: longitude
      };
      // console.log('提交数据:', submitData);

      // 发起网络请求，将 submitData 上传到后台
      uni.request({
        url: './api/submitIssue',
        method: 'POST',
		header:{
			'Authorization': `Bearer ${userInfo.token}`
		},
        data: submitData,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.showToast({ title: '提交成功', icon: 'success' });
            emit('formSubmit', submitData);
            // 重置表单内容
            form.issue = '';
            form.attachmentPath = '';
          } else {
            uni.showToast({
              title: res.data.message || '提交失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('提交错误:', err);
          uni.showToast({ title: '网络错误，提交失败', icon: 'none' });
        },
        complete: () => {
          isSubmitting.value = false;
        }
      });
    },
    fail: (err) => {
      console.error('获取地理位置失败：', err);
      uni.showToast({
        title: '获取位置信息失败，无法打卡',
        icon: 'none'
      });
      isSubmitting.value = false;
    }
  });
};

const startVoiceInput = () => {
  if (!recorderManager) {
    uni.showToast({ title: '录音未初始化', icon: 'none' });
    return;
  }

  isRecording.value = true;
  recorderManager.start({
    format: "mp3",
    duration: 60000,
    sampleRate: 44100,
    numberOfChannels: 1,
    encodeBitRate: 192000
  });
};

const stopVoiceInput = () => {
  if (isRecording.value && recorderManager) {
    recorderManager.stop();
  }
};

/**
 * 将录音文件上传到转写接口（与原有逻辑保持一致）
 */
function uploadAudioForTranscription(tempFilePath) {
  uni.showLoading({
    title: "音频转写中...",
    mask: true
  });

  uni.uploadFile({
    url: "https://api.siliconflow.cn/v1/audio/transcriptions",
    filePath: tempFilePath,
    name: "file",
    formData: {
      model: "FunAudioLLM/SenseVoiceSmall"
    },
    header: {
      Authorization: "Bearer sk-znumummvzniscpunpzxuwixyexuysfkevdkaprhupfhdmtqo"
    },
    success: (uploadRes) => {
      uni.hideLoading();
      try {
        const data = JSON.parse(uploadRes.data);
        // console.log("转写接口返回：", data);
        if (data && data.text) {
          form.issue = data.text;
          uni.showToast({
            title: "语音转文字成功",
            icon: "success"
          });
        } else {
          uni.showToast({
            title: "未获取到转写文本",
            icon: "none"
          });
        }
      } catch (err) {
        console.error("解析转写结果异常：", err);
        uni.showToast({
          title: "转写结果解析失败",
          icon: "none"
        });
      }
    },
    fail: (err) => {
      uni.hideLoading();
      console.error("上传音频或调用转写失败：", err);
      uni.showToast({
        title: "转写失败",
        icon: "none"
      });
    }
  });
}
</script>

<style scoped lang="scss">
.form-section {
  margin-top: 40rpx;
  background: #ffffff;
  padding: 32rpx;
  border-radius: 20rpx;
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.05);
  box-sizing: border-box;

  .form-item {
    margin-bottom: 24rpx;

    .form-label {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;
      margin-bottom: 12rpx;
      display: block;
    }

    .form-textarea {
      width: 100%;
      background-color: #f9f9f9;
      border: 2rpx solid #e0e0e0;
      border-radius: 10rpx;
      padding: 16rpx 20rpx;
      font-size: 26rpx;
      color: #333;
      box-sizing: border-box;
      transition: border 0.2s;
      height: 200rpx;
      resize: none;

      &:focus {
        border-color: #007aff;
        background-color: #ffffff;
      }
    }
  }

  .form-actions {
    margin-top: 32rpx;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 20rpx;
  }

  .btn-primary {
    flex: 2;
    padding: 16rpx;
    font-size: 26rpx;
    font-weight: 500;
    border: none;
    border-radius: 12rpx;
    color: #ffffff;
    text-align: center;
    background: linear-gradient(90deg, #007aff, #00c6ff);
    transition: background-color 0.2s, transform 0.1s;
    opacity: 0.7;

    &:active {
      transform: scale(0.98);
    }

    &:not(:disabled) {
      opacity: 1;
    }
  }

  .btn-warning {
    flex: 1;
    padding: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(90deg, #ff9800, #ffc107);
    border-radius: 12rpx;
    transition: background-color 0.2s, transform 0.1s;

    &:active {
      transform: scale(0.98);
    }
  }
}

.voice-toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.75);
  color: #fff;
  padding: 24rpx 36rpx;
  border-radius: 20rpx;
  font-size: 28rpx;
  z-index: 999;
  text-align: center;
  animation: fade-in-out 1s ease-in-out infinite alternate;
}

@keyframes fade-in-out {
  0% {
    opacity: 0.6;
  }
  100% {
    opacity: 1;
  }
}

/* 语音输入相关样式 */
.record-hint {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 200px;
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 200;
}

.record-icon {
  width: 80px;
  height: 80px;
  background-color: #409eff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
}

.record-icon .iconfont {
  color: #ffffff;
  font-size: 40px;
}

.record-info {
  text-align: center;
}

.record-info text {
  color: #ffffff;
  font-size: 16px;
  display: block;
  margin-bottom: 10px;
}

.record-volume {
  display: flex;
  align-items: flex-end;
  justify-content: center;
  height: 20px;
}

.volume-bar {
  width: 4px;
  margin: 0 2px;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
}

.volume-bar.active {
  background-color: #ffffff;
}
</style>
